<template>
<el-card>
  <!-- 商品运费模板 -->
  <div class="page">
    <h3 class="applyRecode">新增运费模板</h3>
    <el-form class="form" :model="form" :rules="rules" ref="form" label-width="105px">
      <el-form-item class="jprice" size="small" label="计价方式：" prop="valuationType">
        <el-select v-model="form.valuationType" placeholder="请选择计价方式">
          <el-option v-for="(item, index) in items" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item size="small" label="模板名称：" prop="templateName">
        <el-input placeholder="请输入模板名称" v-model="form.templateName"></el-input>
      </el-form-item>
      <el-form-item label="运送方式：">
        <p class="warn two">除指定区域外，其他地区费用采用“默认运费”</p>
        <div class="lonely" label-width="">
          <el-form-item size="small" label="默认运费" prop="goodsInitNum">
            <el-input placeholder="" v-model="form.goodsInitNum" @change = "changeMoney1(form.goodsInitNum, 'goodsInitNum')"></el-input>
          </el-form-item>
          <el-form-item size="small" label="件内" prop="goodsInitFreight">
            <el-input placeholder="" v-model="form.goodsInitFreight"></el-input>元，
          </el-form-item>
          <el-form-item size="small" label="每增加件" prop="goodsAddNum">
            <el-input placeholder="" v-model="form.goodsAddNum"></el-input>件，
          </el-form-item>
          <el-form-item size="small" label="增加运费" prop="goodsAddFreight">
            <el-input placeholder="" v-model="form.goodsAddFreight"  @change = "changeMoney1(form.goodsAddFreight, 'goodsAddFreight')"></el-input>元
          </el-form-item>
        </div>
        <div class="addicon" @click = "push">
          <i class="el-icon-circle-plus-outline iconsize"></i>
          <p class="icondesc">为指定地区城市设置运费</p>
        </div>
      </el-form-item>
      <div class="tables">
        <el-table :data="form.tableData">
          <el-table-column label="区域" align="center" width="270px">
            <template slot-scope="scope">
              <el-button @click="province(scope.$index)" type="text" size="small" v-if = "!scope.row.areaNames">编辑</el-button>
              <span>{{ scope.row.areaNames }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsInitNum" label="首件（件）" align="center">
            <template slot-scope="scope">
              <el-form-item :prop = "`tableData.${scope.$index}.goodsInitNum`" :rules="rules.goodsInitNum" class = "form-item" label-width="0">
                <el-input size="small" v-model = "scope.row.goodsInitNum"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goodsInitFreight" label="运费（元）" align="center">
            <template slot-scope="scope">
              <el-form-item :prop = "`tableData.${scope.$index}.goodsInitFreight`" :rules="rules.goodsInitFreight"  class = "form-item" label-width="0">
                <el-input size="small" v-model = "scope.row.goodsInitFreight" @change = "changeMoney(scope.row.goodsInitFreight, scope.$index, 'goodsInitFreight')"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goodsAddNum" label="续件（件）" align="center">
            <template slot-scope="scope">
              <el-form-item :prop = "`tableData.${scope.$index}.goodsAddNum`" :rules="rules.goodsAddNum"  class = "form-item" label-width="0">
                <el-input size="small" v-model = "scope.row.goodsAddNum"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goodsAddFreight" label="运费（元）" align="center">
            <template slot-scope="scope">
              <el-form-item :prop = "`tableData.${scope.$index}.goodsAddFreight`" :rules="rules.goodsAddFreight"  class = "form-item" label-width="0">
              <el-input size="small" v-model = "scope.row.goodsAddFreight"  @change = "changeMoney(scope.row.goodsAddFreight, scope.$index, 'goodsAddFreight')"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button @click="dele(scope.$index)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="" :visible.sync="dialogVisible" width="30%">
        <el-transfer v-model="value1" :titles="['可选省，市，区', '已选省，市，区']" :data="areaName" :title="titarr"></el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitData">确 定</el-button>
        </span>
      </el-dialog>
      <div class="btndiv">
        <el-button type="primary" size="small" @click="cancel">取消</el-button>
        <el-button type="primary" size="small" @click="sure">确认</el-button>
      </div>
    </el-form>
  </div>
</el-card>
</template>
<script>
export default {
  name: 'newly',
  data () {
    return {
      titarr: ['待选区域', '已选区域'],
      areaName: [],
      value1: [],
      items: [
        {
          label: '按商品计费',
          value: '1'
        },
        {
          label: '按店铺计费',
          value: '2'
        }
      ],
      dialogVisible: false,
      form: {
        valuationType: '',
        templateName: '',
        goodsInitNum: '',
        goodsInitFreight: '',
        goodsAddNum: '',
        goodsAddFreight: '',
        tableData: []
      },
      rules: {
        valuationType: [
          { required: true, message: '请选择计价方式', trigger: 'change' }
        ],
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        goodsInitNum: [
          { required: true, message: '请填写！', trigger: 'blur' },
          { pattern: /^\d{1,16}?$/, message: '格式不正确', trigger: 'blur' }
        ],
        goodsInitFreight: [
          { required: true, message: '请填写！', trigger: 'blur' },
          { pattern: /^\d{1,16}(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
        ],
        goodsAddNum: [
          { required: true, message: '请填写！', trigger: 'blur' },
          { pattern: /^[0-9]{1,16}?$/, message: '格式不正确', trigger: 'blur' }
        ],
        goodsAddFreight: [
          { required: true, message: '请填写！', trigger: 'blur' },
          { pattern: /^\d{1,16}(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
        ]
      },
      index: 0
    }
  },
  created () {
    this.sheng()
    this.init()
  },
  methods: {
    //点击编辑  页面回显
    init () {
      if (this.$route.query.tempid) {
        this.$tkAjax.get(`${this.$config.baseUrl}/order/shippingTemplate/getShippingTemplateById?shippingTemplateId=` + this.$route.query.tempid).then(res => {
          this.form = res.data.content
          this.form.tableData = res.data.content.shippingTemplateAreaList
        }).catch(err => {
          this.$message.warning(err.data.message)
        })
      }
    },
    //编辑显示页
    edit () {
      this.$tkAjax.post(`${this.$config.baseUrl}/order/shippingTemplate/updateShippingTemplateById`, {}, {
        params: {
          condition: {
            templateId: this.$route.query.tempid,
            merchantId: this.$store.state.merchantId,
            valuationType: this.form.valuationType,
            templateName: this.form.templateName,
            goodsInitNum: this.form.goodsInitNum,
            goodsInitFreight: this.form.goodsInitFreight,
            goodsAddNum: this.form.goodsAddNum,
            goodsAddFreight: this.form.goodsAddFreight,
            shippingTemplateAreaList: this.form.tableData
          }
        }
      }).then(res => {
        this.$message.success(res.data.message)
        this.$router.push('/templates')
      }).catch(err => {
        this.$message.warning(err.data.message)
      })
    },
    changeMoney (value, index, key) {
      if ((/^\d{1,16}.\d{3,}?$/).test(value)) {
        this.form.tableData[index][key] = (value * 1).toFixed(2)
      }
    },
    changeMoney1 (value, key) {
      if ((/^\d{1,16}.\d{3,}?$/).test(value)) {
        this.form[key] = (value * 1).toFixed(2)
      }
    },
    //省
    sheng () {
      let json = {
        pid: '0'
      }
      this.$tkAjax.get(`${this.$config.baseUrl}/system/area/getAreaWithCascade`, {
        params: json
      }).then(res => {
        this.areaName = res.data.content.map(item => {
          return {
            key: item.areaId,
            label: item.areaName,
            disabled: false
          }
        })
      }).catch(err => {
        this.$message.warning(err.data.message)
      })
    },
    //选择省份
    province (index) {
      this.index = index
      this.dialogVisible = true
    },
    dele (index) {
      if (this.form.tableData[index] && Array.isArray(this.form.tableData[index].areaNames)) {
        let arr = this.form.tableData[index].areaNames.split(',')
        this.areaName = this.areaName.map(item => {
          let index = arr.findIndex(it => {
            return it === item.label
          })
          if (index !== -1) {
            item.disabled = false
          }
          return item
        })
      }

      this.form.tableData.splice(index, 1)
    },
    submitData () {
      if (this.value1.length === this.areaName.length) {
        this.$message.warning('无效的操作，不可全部选择地区')
        return false
      }
      this.form.tableData[this.index].areaNames = this.value1.map(item => {
        return this.areaName.find(it => {
          return it.key === item
        }).label
      }).join(',')
      this.form.tableData[this.index].areaIds = this.value1.map(item => {
        return this.areaName.find(it => {
          return it.key === item
        }).key
      }).join(',')
      this.areaName = this.areaName.map(item => {
        let index = this.value1.findIndex(it => {
          return it === item.key
        })
        if (index !== -1) {
          item.disabled = true
        }
        return item
      })
      this.value1 = []
      this.$set(this.form.tableData, this.index, this.form.tableData[this.index])
      this.dialogVisible = false
    },
    //确认
    sure () {
      this.$refs.form.validate(valid => {
        if (valid) {
          let index = this.form.tableData.findIndex(item => {
            return !item.areaIds
          })
          if (index !== -1) {
            this.$message.warning('请选择地区')
            return false
          }
          if (this.$route.query.tempid) {
            this.edit()
          } else {
            this.$tkAjax.post(`${this.$config.baseUrl}/order/shippingTemplate/saveShippingTemplateByStr`, {}, {
              params: {
                condition: {
                  merchantId: this.$store.state.merchantId,
                  valuationType: this.form.valuationType,
                  templateName: this.form.templateName,
                  goodsInitNum: this.form.goodsInitNum,
                  goodsInitFreight: this.form.goodsInitFreight,
                  goodsAddNum: this.form.goodsAddNum,
                  goodsAddFreight: this.form.goodsAddFreight,
                  shippingTemplateAreaList: this.form.tableData
                }
              }
            }).then(res => {
              this.$message.success(res.data.message)
              this.$router.push('/templates')
            }).catch(err => {
              this.$message.warning(err.data.message)
            })
          }
        }
      })
    },
    cancel () {
      this.$router.push('/templates')
    },
    push () {
      this.form.tableData.push({
        goodsInitNum: '',
        goodsInitFreight: '',
        goodsAddNum: '',
        goodsAddFreight: ''
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.page {
  // background: #EEF9FB;
  .form {
    width: 80%;
    margin-left: 50px;
    .jprice {
      .el-form-item__content {
        .el-select {
          width: 100%;
        }
      }
    }
    .tables {
      width: 100%;
      padding-bottom: 20px;
      padding-left: 125px;
      .form-item{
        margin: 22px 0;
      }
    }
    .proces {
      display: flex;
    }
    .warn {
      display: inline;
      color: #f00;
      font-size: 12px;
      margin-left: 20px;
    }
    .warn.two{
      margin-left: 0;
    }
    .lonely {
      background-color: #f5f5f5;
      display: flex;
      padding: 0 10px;
      .el-form-item {
        margin-top: 15px;
        margin-bottom: 15px;
        .el-form-item__content {
          display: flex;
          .el-input {
            width: 100px;
          }
        }
      }
      .el-form-item:nth-of-type(2), .el-form-item:nth-of-type(3), .el-form-item:nth-of-type(4) {
        .el-input {
          margin-right: 10px;
        }
      }
    }
    .addicon {
      display: flex;
      align-items: center;
      .iconsize {
        font-size: 20px;
      }
      .icondesc {
        color: #f00;
        font-size: 12px;
        padding-left: 10px;
      }
    }
    .btndiv {
      text-align: center;
      .el-button {
        border-radius: 4px;
      }
    }
  }
}
</style>
